/**
 * 
 */
package com.wsj.web.action.researchReport;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.wsj.service.IHomeSiteResearchReportFileUploadServ;
import com.wsj.service.IUserManagerServ;
import com.wsj.util.exception.BusinessException;
import com.wsj.util.page.PageResultSet;
import com.wsj.util.tool.DateUtil;
import com.wsj.util.tool.FileUplaodAndManageForStorage;
import com.wsj.util.tool.HtmlCreateObj;
import com.wsj.util.tool.NumberUtil;
import com.wsj.util.tool.RequestUtils;
import com.wsj.web.action.BaseAction;
import com.wsj.web.constant.homeSiteNews.HomeSiteNewsConstant;
import com.wsj.web.constant.page.PageContent;
import com.wsj.web.form.researchReport.HomeSiteResearchReportFileUploadForm;
import com.wsj.web.vo.homeSite.BmFileType;
import com.wsj.web.vo.homeSite.BmResearchInstitution;
import com.wsj.web.vo.homeSite.BmResearchReportType;
import com.wsj.web.vo.homeSite.CmQuotedCompany;
import com.wsj.web.vo.homeSite.HomeSiteUploadFile;
import com.wsj.web.vo.homeSite.UserBase;

/**
 * @author fengbin  createTime:2009-7-25
 * 
 */
public class HomeSiteResearchReportFileUploadAction extends BaseAction {

	
	/*********
	 * 研究报告上传服务层
	 */
	 private IHomeSiteResearchReportFileUploadServ homeSiteResearchReportFileUploadServ;
	 
	 
	 /********
	  * 文件上传
	  * @return
	  */
	 private  FileUplaodAndManageForStorage fileUplaodAndManageForStorage;
	 
	 /*****
	  * 用户对象
	  * @return
	  */
	 private IUserManagerServ  userManagerServ;
	 
	 /******
	  * 生成html文件
	  * @return
	  */
	 private HtmlCreateObj  htmlCreateObj;
	 
	 
	public HtmlCreateObj getHtmlCreateObj() {
		return htmlCreateObj;
	}

	public void setHtmlCreateObj(HtmlCreateObj htmlCreateObj) {
		this.htmlCreateObj = htmlCreateObj;
	}

	public IUserManagerServ getUserManagerServ() {
		return userManagerServ;
	}

	public void setUserManagerServ(IUserManagerServ userManagerServ) {
		this.userManagerServ = userManagerServ;
	}

	public FileUplaodAndManageForStorage getFileUplaodAndManageForStorage() {
		return fileUplaodAndManageForStorage;
	}

	public void setFileUplaodAndManageForStorage(
			FileUplaodAndManageForStorage fileUplaodAndManageForStorage) {
		this.fileUplaodAndManageForStorage = fileUplaodAndManageForStorage;
	}

	public IHomeSiteResearchReportFileUploadServ getHomeSiteResearchReportFileUploadServ() {
		return homeSiteResearchReportFileUploadServ;
	}

	public void setHomeSiteResearchReportFileUploadServ(
			IHomeSiteResearchReportFileUploadServ homeSiteResearchReportFileUploadServ) {
		this.homeSiteResearchReportFileUploadServ = homeSiteResearchReportFileUploadServ;
	}
	
	
	/*******
	 * 获取数据,跳转到上传研究报告页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward toAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		
		  //获取文件类型列表
		  this.getFileTypeListList(request);
		
		  //获取研究机构列表
		  this.getBmResearchInstitutionList(request);
		
		  //研究报告类型列表
		  this.getBmResearchReportTypeList(request);
		
		  //跳转到研究报告添加页面
		  return mapping.findForward("researchReportFileUploadAdd");
		
	}
	
	
	/*************
	 * 添加研究报告
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		
		String toPage="toAdd";
		
		HomeSiteResearchReportFileUploadForm homeSiteResearchReportFileUploadForm = (HomeSiteResearchReportFileUploadForm)form;
		
		//获取受影响的主要股票
		CmQuotedCompany cmQuotedCompany = this.getHomeSiteResearchReportFileUploadServ().loadCmQuotedCompanyByStockNumId(String.valueOf(homeSiteResearchReportFileUploadForm.getCmQuotedCompanyId()));
		
		//获取上传文件类型
		BmFileType  bmFileType = this.getHomeSiteResearchReportFileUploadServ().getBmFileTypeById(homeSiteResearchReportFileUploadForm.getBmFileTypeId());
		
		//获取研究机构
		BmResearchInstitution bmResearchInstitution = this.getHomeSiteResearchReportFileUploadServ().getBmResearchInstitutionById(homeSiteResearchReportFileUploadForm.getBmResearchInstitutionId());
		
		//获取报告类型
		BmResearchReportType bmResearchReportType = this.getHomeSiteResearchReportFileUploadServ().getBmResearchReportTypeById(homeSiteResearchReportFileUploadForm.getBmResearchReportTypeId());
		
		HomeSiteUploadFile  homeSiteUploadFile = new HomeSiteUploadFile();
		
		
		homeSiteUploadFile.setFileTitle(homeSiteResearchReportFileUploadForm.getFileTitle());
		homeSiteUploadFile.setStockName(homeSiteResearchReportFileUploadForm.getStockName());
		homeSiteUploadFile.setStatus(new Short("0"));
		homeSiteUploadFile.setFileDescription(homeSiteResearchReportFileUploadForm.getFileDescription());
		homeSiteUploadFile.setGmtCreate(new Date());
		homeSiteUploadFile.setGmtModified(new Date());
		homeSiteUploadFile.setAttention(homeSiteResearchReportFileUploadForm.getAttention());
		homeSiteUploadFile.setCreateReportDate(DateUtil.getDate(homeSiteResearchReportFileUploadForm.getCreateReportDateStr()));
		
		homeSiteUploadFile.setCmQuotedCompany(cmQuotedCompany);
		homeSiteUploadFile.setBmFileType(bmFileType);
		homeSiteUploadFile.setBmResearchInstitution(bmResearchInstitution);
		homeSiteUploadFile.setBmResearchReportType(bmResearchReportType);
		
		//获取当前登陆用户
		UserBase userBase = this.getUserManagerServ().getUserBaseById(this.getUserIdFromSession(request));
		if(userBase == null){
			toPage = "error";
			request.setAttribute("msg", "加载当前用户出错");
			return mapping.findForward(toPage);
		}
		
		homeSiteUploadFile.setUserBase(userBase);
		
		boolean isok =false;
		//上传文件
		if(homeSiteResearchReportFileUploadForm.getFormFile()!=null 
				&& homeSiteResearchReportFileUploadForm.getFormFile().getFileName()!=null
				&& !homeSiteResearchReportFileUploadForm.getFormFile().getFileName().equals("")){
			
			FormFile uploadFile = homeSiteResearchReportFileUploadForm.getFormFile();
			fileUplaodAndManageForStorage.setMyFiles(uploadFile);
			fileUplaodAndManageForStorage.setCheckFileTrueType(false);
			fileUplaodAndManageForStorage.setPassFileExtenSionName(HomeSiteNewsConstant.REPORT_EXT_NAME);
			//20M
			fileUplaodAndManageForStorage.setMaxFileSize(10485760 * 2);
			//上传的路径
			fileUplaodAndManageForStorage.setPath(HomeSiteNewsConstant.REPORT_FILE_PATH);
			
			String fileName = this.fileUplaodAndManageForStorage.uploadFile(request, "");
			homeSiteUploadFile.setFileName(fileName);
		}
		
		if(homeSiteUploadFile.getFileName()!=null  && !homeSiteUploadFile.getFileName().equals("")){
			isok = this.getHomeSiteResearchReportFileUploadServ().addHomeSiteUploadFile(homeSiteUploadFile);
			
			//生成研究报告的页面.
			if(isok){
				boolean createReportPage=this.createReportHtml(homeSiteUploadFile, request, response);
				}
			
			if(!isok){
				toPage = "error";
				request.setAttribute("msg", "添加研究报告出错");
			}
		}else{
			toPage = "error";
			request.setAttribute("msg", "上传文件出错");
		}
		
		
		return mapping.findForward(toPage);
		
	}
	
	
	
	
    /********
     * 生成研究报告页面
     * @return
     * @throws BusinessException 
     */
	private boolean createReportHtml(HomeSiteUploadFile  homeSiteUploadFile,HttpServletRequest request,
			HttpServletResponse response) throws BusinessException {
		
		boolean isok=false;
		 try {
			//生成静态页面
			 String filePath=HomeSiteNewsConstant.reportHead+homeSiteUploadFile.getId()+".html";
			htmlCreateObj.setCreateFileParament(RequestUtils.getRequestHost(request)+HomeSiteNewsConstant.reportPath+homeSiteUploadFile.getId(), "html/report/", filePath);
			 //生成静态页面
			htmlCreateObj.createHtmlFile(request, response);
			//设置静态文件路径
			HomeSiteUploadFile  dbHomeSiteUploadFile =this.getHomeSiteResearchReportFileUploadServ().getHomeSiteUploadFileById(homeSiteUploadFile.getId());
			dbHomeSiteUploadFile.setFilePath(filePath);
			this.getHomeSiteResearchReportFileUploadServ().updateHomeSiteUploadFile(dbHomeSiteUploadFile);
			
			isok =true;
			
		} catch (BusinessException e) {
			throw new BusinessException(e);
		}
		
		return isok;
		
	}

	/****************
	 * 跳转到更新页面
	 */
	public ActionForward toUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		  //获取文件类型列表
		  this.getFileTypeListList(request);
		
		  //获取研究机构列表
		  this.getBmResearchInstitutionList(request);
		
		  //研究报告类型列表
		  this.getBmResearchReportTypeList(request);
		
		HomeSiteUploadFile homeSiteUploadFile = null;
		String id=request.getParameter("id");
		if(id!=null  && NumberUtil.isNumber(id)){
			homeSiteUploadFile =this.getHomeSiteResearchReportFileUploadServ().getHomeSiteUploadFileById(Integer.valueOf(id));	
		}
		
		request.setAttribute("homeSiteUploadFile", homeSiteUploadFile);
		
		return mapping.findForward("researchReportFileUploadUpdate");
		
	}
	
	
	/***********
	 * 更新研究报告
	 */
	public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		
        String toPage="toList";
        
        String backUrl = request.getParameter("backUrl");
		
		HomeSiteResearchReportFileUploadForm homeSiteResearchReportFileUploadForm = (HomeSiteResearchReportFileUploadForm)form;
		
		HomeSiteUploadFile dbHomeSiteUploadFile = this.getHomeSiteResearchReportFileUploadServ().getHomeSiteUploadFileById(homeSiteResearchReportFileUploadForm.getId());
		
		//获取受影响的主要股票
		CmQuotedCompany cmQuotedCompany = this.getHomeSiteResearchReportFileUploadServ().loadCmQuotedCompanyByStockNumId(String.valueOf(homeSiteResearchReportFileUploadForm.getCmQuotedCompanyId()));
		
		//获取上传文件类型
		BmFileType  bmFileType = this.getHomeSiteResearchReportFileUploadServ().getBmFileTypeById(homeSiteResearchReportFileUploadForm.getBmFileTypeId());
		
		//获取研究机构
		BmResearchInstitution bmResearchInstitution = this.getHomeSiteResearchReportFileUploadServ().getBmResearchInstitutionById(homeSiteResearchReportFileUploadForm.getBmResearchInstitutionId());
		
		//获取报告类型
		BmResearchReportType bmResearchReportType = this.getHomeSiteResearchReportFileUploadServ().getBmResearchReportTypeById(homeSiteResearchReportFileUploadForm.getBmResearchReportTypeId());
		
		dbHomeSiteUploadFile.setFileTitle(homeSiteResearchReportFileUploadForm.getFileTitle());
		dbHomeSiteUploadFile.setStockName(homeSiteResearchReportFileUploadForm.getStockName());
		
		if(homeSiteResearchReportFileUploadForm.getStatus()!=null){
			dbHomeSiteUploadFile.setStatus(homeSiteResearchReportFileUploadForm.getStatus());	
		}
		
		dbHomeSiteUploadFile.setFileDescription(homeSiteResearchReportFileUploadForm.getFileDescription());
		dbHomeSiteUploadFile.setGmtModified(new Date());
		dbHomeSiteUploadFile.setAttention(homeSiteResearchReportFileUploadForm.getAttention());
		if(homeSiteResearchReportFileUploadForm.getCreateReportDateStr()!=null && !homeSiteResearchReportFileUploadForm.getCreateReportDateStr().equals("")){
			dbHomeSiteUploadFile.setCreateReportDate(DateUtil.getDate(homeSiteResearchReportFileUploadForm.getCreateReportDateStr()));			
		}
		
		
		dbHomeSiteUploadFile.setCmQuotedCompany(cmQuotedCompany);
		dbHomeSiteUploadFile.setBmFileType(bmFileType);
		dbHomeSiteUploadFile.setBmResearchInstitution(bmResearchInstitution);
		dbHomeSiteUploadFile.setBmResearchReportType(bmResearchReportType);
		
		//获取当前登陆用户
		UserBase userBase = this.getUserManagerServ().getUserBaseById(this.getUserIdFromSession(request));
		if(userBase == null){
			toPage = "error";
			request.setAttribute("msg", "加载当前用户出错");
			return mapping.findForward(toPage);
		}
		
		dbHomeSiteUploadFile.setUserBase(userBase);
		
		
		//上传文件
		if(homeSiteResearchReportFileUploadForm.getFormFile()!=null 
				&& homeSiteResearchReportFileUploadForm.getFormFile().getFileName()!=null
				&& !homeSiteResearchReportFileUploadForm.getFormFile().getFileName().equals("")){
			
			
			FormFile uploadFile = homeSiteResearchReportFileUploadForm.getFormFile();
			fileUplaodAndManageForStorage.setMyFiles(uploadFile);
			fileUplaodAndManageForStorage.setCheckFileTrueType(false);
			fileUplaodAndManageForStorage.setPassFileExtenSionName(HomeSiteNewsConstant.REPORT_EXT_NAME);
			//20M
			fileUplaodAndManageForStorage.setMaxFileSize(10485760 * 2);
			//上传的路径
			fileUplaodAndManageForStorage.setPath(HomeSiteNewsConstant.REPORT_FILE_PATH);
			
			String oldfileName ="";
			//因为上传的文件如果上除出错了.那么文件的类型也变化了.比如上传了出错的pdf,然后修改成doc.
			//那么会出问题,现在需要删除老文件.然后直接上传一个新的文件.
			/****
			 *  FiXME ! fb 需要删除老的文件.
			 */ 

			
			String fileName = this.fileUplaodAndManageForStorage.uploadFile(request, oldfileName);
			if(fileName!=null && !fileName.equals("")){
				dbHomeSiteUploadFile.setFileName(fileName);
			}
			
		}
		
		boolean isok = this.getHomeSiteResearchReportFileUploadServ().updateHomeSiteUploadFile(dbHomeSiteUploadFile);
		
//		生成研究报告的页面.
		if(isok){
			boolean createReportPage=this.createReportHtml(dbHomeSiteUploadFile, request, response);
			}
		
		if(!isok){
			toPage = "error";
			request.setAttribute("msg", "更新研究报告出错");
		}
		
		if(backUrl!=null && !backUrl.equals("")){
			return new ActionForward(backUrl);
		}else{
			return mapping.findForward(toPage);	
		}
		
	}
	
	
	/********
	 * 删除研究报告
	 */
	public ActionForward del(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		    String toPage="researchReportFileUploadList";
	        
	        String backUrl = request.getParameter("backUrl");
			
			HomeSiteResearchReportFileUploadForm homeSiteResearchReportFileUploadForm = (HomeSiteResearchReportFileUploadForm)form;
			
			HomeSiteUploadFile dbHomeSiteUploadFile = this.getHomeSiteResearchReportFileUploadServ().getHomeSiteUploadFileById(homeSiteResearchReportFileUploadForm.getId());
			
			dbHomeSiteUploadFile.setStatus(HomeSiteNewsConstant.STATUS_DEL);
			
	       boolean isok = this.getHomeSiteResearchReportFileUploadServ().updateHomeSiteUploadFile(dbHomeSiteUploadFile);
	        if(!isok){
				toPage = "error";
				request.setAttribute("msg", "更新研究报告出错");
			}
			
			if(backUrl!=null && !backUrl.equals("")){
				return new ActionForward(backUrl);
			}else{
				return mapping.findForward(toPage);	
			}
			
	}
	
	/***********
	 * 跳转到研究报告管理搜索列表
	 */
	public ActionForward toList(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		
		 //获取文件类型列表
		  this.getFileTypeListList(request);
		
		  //获取研究机构列表
		  this.getBmResearchInstitutionList(request);
		  
		  return mapping.findForward("researchReportFileUploadList");
		  
	}
	
	
	
	/***********
	 * 获取列表
	 * 
	 * 通过  文件名  文件类型  研究机构  发布开始时间 发布结束时间 搜索研究报告  
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		  
          //获取文件类型列表
		  this.getFileTypeListList(request);
		
		  //获取研究机构列表
		  this.getBmResearchInstitutionList(request);
		  
		   HomeSiteResearchReportFileUploadForm homeSiteResearchReportFileUploadForm =this.createSearchForm(request);
		   request.setAttribute("homeSiteResearchReportFileUploadForm", homeSiteResearchReportFileUploadForm);
		   
		   String pageStr = request.getParameter("page");
		   String pageSizeStr = request.getParameter("pageSize");
		   int page = HomeSiteNewsConstant.DEFAULT_PAGE;
		   int pageSieze = HomeSiteNewsConstant.DEFAULT_PAGE_SIZE;
		   if(pageStr!=null && NumberUtil.isNumber(pageStr)){
			   page = Integer.valueOf(pageStr);
		   }
		   
          if(pageSizeStr!=null && NumberUtil.isNumber(pageSizeStr)){
        	  pageSieze = Integer.valueOf(pageSizeStr);
		   }
		   
          PageResultSet  pageResultSet =this.getHomeSiteResearchReportFileUploadServ().searchResearchReportList(homeSiteResearchReportFileUploadForm ,page, pageSieze);
		 
           if(pageResultSet!=null)
			{
			  	// 设置上一页
				request.setAttribute(PageContent.backPage,pageResultSet.getBackPage());
				//下一页
				request.setAttribute(PageContent.nextPage,pageResultSet.getNextPage());
				//当前页
				request.setAttribute(PageContent.curPage,pageResultSet.getCurPage());
				
				//总共页数
				request.setAttribute(PageContent.allPage,pageResultSet.getAllPage());
				//大小
				request.setAttribute(PageContent.pageSize,pageResultSet.getPageSize());
				
				request.setAttribute(PageContent.recordNum, pageResultSet.getRecordNum());
				
				//结果集
				List homeSiteUploadFileList = pageResultSet.getResult();
				request.setAttribute("homeSiteUploadFileList", homeSiteUploadFileList);
				
			}
		   return mapping.findForward("researchReportFileUploadList");
	}

	
	/*********
	 * 设置搜索的参数
	 * @param request
	 * @return
	 */
	private HomeSiteResearchReportFileUploadForm createSearchForm(HttpServletRequest request) {
		
		HomeSiteResearchReportFileUploadForm  homeSiteResearchReportFileUploadForm = new HomeSiteResearchReportFileUploadForm();
		try {
			String fileTitle = request.getParameter("fileTitle");
			String bmFileTypeIdStr = request.getParameter("bmFileTypeId");
			String bmResearchInstitutionIdStr  = request.getParameter("bmResearchInstitutionId");
			String statusStr = request.getParameter("status");
			String gmtCreateStr  = request.getParameter("gmtCreateStr");
			String gmtCreateEndStr  = request.getParameter("gmtCreateEndStr");
			
			if(fileTitle!=null  && !fileTitle.equals("") && !fileTitle.equals("null")){
				homeSiteResearchReportFileUploadForm.setFileTitle(new String(fileTitle.trim().getBytes("ISO-8859-1"),"UTF-8"));
			}
			
            if(bmFileTypeIdStr!=null  && !bmFileTypeIdStr.equals("") && !bmFileTypeIdStr.equals("-1")){
			   homeSiteResearchReportFileUploadForm.setBmFileTypeId(Integer.valueOf(bmFileTypeIdStr));
			}
      
            if(bmResearchInstitutionIdStr!=null  && !bmResearchInstitutionIdStr.equals("") && !bmResearchInstitutionIdStr.equals("-1")){
			   homeSiteResearchReportFileUploadForm.setBmResearchInstitutionId(Integer.valueOf(bmResearchInstitutionIdStr));
			}
      
             if(statusStr!=null  && !statusStr.equals("") && !statusStr.equals("null")){
			   homeSiteResearchReportFileUploadForm.setStatus(Short.valueOf(statusStr));
			}
      
             if(gmtCreateStr!=null  && !gmtCreateStr.equals("")){
			   homeSiteResearchReportFileUploadForm.setGmtCreateStr(gmtCreateStr);
			}
      
             if(gmtCreateEndStr!=null  && !gmtCreateEndStr.equals("")){
			   homeSiteResearchReportFileUploadForm.setGmtCreateEndStr(gmtCreateEndStr);
			}
             
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
       return homeSiteResearchReportFileUploadForm;
		
		
	}

	/*******
	 * 研究报告类型列表
	 * @param request
	 */
	private void getBmResearchReportTypeList(HttpServletRequest request) {
		
		try {
			List<BmResearchReportType>  bmResearchReportTypeList = this.homeSiteResearchReportFileUploadServ.getBmResearchReportTypeList();
			request.setAttribute("bmResearchReportTypeList", bmResearchReportTypeList);
		} catch (BusinessException e) {
			this.getLogger().error("加载研究报告类型列表出错!",e);
		}
		
	}

	/******
	 * 获取研究机构列表
	 * @param request
	 */
	private void getBmResearchInstitutionList(HttpServletRequest request) {
		
		try {
			List<BmResearchInstitution> bmResearchInstitutionList = this.homeSiteResearchReportFileUploadServ.getBmResearchInstitutionList();
			request.setAttribute("bmResearchInstitutionList", bmResearchInstitutionList);
		} catch (BusinessException e) {
			this.getLogger().error("获取研究机构列表出错!",e);
		}
		
	}

	/********
	 * 获取文件类型列表
	 * @param request
	 */
	private void getFileTypeListList(HttpServletRequest request) {
		
		try {
			List<BmFileType> bmFileType = this.homeSiteResearchReportFileUploadServ.getFileTypeListList();
			request.setAttribute("bmFileTypeList", bmFileType);
		} catch (BusinessException e) {
			this.getLogger().error("获取文件类型列表",e);
		}
		
	}
	
	
	
	 
	 
}
